package com.cjst.controller.api.login;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cjst.controller.base.BaseController;
import com.cjst.dto.SysDictDto;
import com.cjst.pojo.sys.SysOffice;
import com.cjst.pojo.sys.SysUser;
import com.cjst.sdp.util.MenuNode;
import com.cjst.sdp.util.ShiroKit;
import com.cjst.service.redis.RedisService;
import com.cjst.service.sys.SysDictService;
import com.cjst.service.sys.SysMenuService;
import com.cjst.service.sys.SysOfficeService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.ErroResult;
import com.cjst.util.UserPrincipalUtil;
import com.cjst.util.code.VerifyCode;
import com.cjst.util.common.CommonConstant;
import com.cjst.util.common.GenerativeToken;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;

/**
 * APP登陆相关
 * @author yj
 *
 */
@Controller
@RequestMapping("/api")
public class LoginController extends BaseController{
	protected final Logger log = Logger.getLogger(LoginController.class);
	@Autowired
	private RedisService redisService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysDictService dictService;
	@Autowired
	private SysUserService userService;
	@Autowired
	private SysOfficeService sysOfficeService;
	/**
	 * 获取验证码
	 * @param imei
	 * @return
	 */
	@RequestMapping(value="/getCode",method = RequestMethod.POST)
	@ResponseBody
	public String getCode(){
		try {
			String code=VerifyCode.generateTextCode(0, 4, null);
			//生成codekey
			String codeKey=GenerativeToken.getToken();
			HashMap<String, String> map=new HashMap<String, String>();
			map.put("code", code);
			map.put("codeKey", codeKey);
			redisService.setObjByTime(CommonConstant.VERIFY_CODE+codeKey, code, 300);           //存验证码5分钟
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	/**
	 * 登陆过期，重新获取验证码
	 * @return
	 */
	@RequestMapping(value="/getCodeAge",method = RequestMethod.GET)
	@ResponseBody
	public String getCodeAges(){
		try {
			String code=VerifyCode.generateTextCode(0, 4, null);
			//生成codekey
			String codeKey=GenerativeToken.getToken();
			HashMap<String, String> map=new HashMap<String, String>();
			map.put("code", code);
			map.put("codeKey", codeKey);
			redisService.setObjByTime(CommonConstant.VERIFY_CODE+codeKey, code, 180);			//存验证码5分钟
			ResultObj robj = new ResultObj(ResultCode.RESULT_PARAM_ERROR, "登陆过期",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	/**
	 * 登陆
	 * @param userName
	 * @param passWord
	 * @param code
	 * @param codeKey
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/login",method = RequestMethod.POST)
	@ResponseBody
    public String login(String userName,String passWord,String code,String codeKey)  {
		try {
			if(userName==null || userName.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "用户名不为空",null);
				return robj.toString();
			}
			if(passWord==null || passWord.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "密码不能为空",null);
				return robj.toString();
			}
			if(codeKey==null || codeKey.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码过期",null);
				return robj.toString();
			}
			Object codes=redisService.getObj(CommonConstant.VERIFY_CODE+codeKey);
			if(codes==null){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码过期",null);
				return robj.toString();
			}
			if(code==null || code.length()==0){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码过期",null);
				return robj.toString();
			}
			if(!codes.toString().equals(code)){
				ResultObj robj = new ResultObj(ResultCode.RESULT_PHONE_NOT_CODE, "验证码错误",null);
				return robj.toString();
			}
			userName=userName.trim();
			passWord=passWord.trim();
			WherePrams wheres=Method.where("userName", C.EQ, userName);
			wheres.and("status", C.EQ, "1");
			List<SysUser> sysUserList=sysUserService.list(wheres);
			if(sysUserList==null || sysUserList.size()==0){
				log.info("=============客户端平台账号不存在");
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "客户端平台账号不存在,请联系管理员",null);
				return robj.toString();
			}
			if(sysUserList.size()>1){
				log.info("=============客户端平台账号异常");
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "客户端平台账号异常,请联系管理员",null);
				return robj.toString();
			}
			SysUser sysUser=sysUserList.get(0);
			String md5password = ShiroKit.md5(passWord, sysUser.getSalt());
			//String md5password = MethodUtil.getMD5(passWord, "UTF-8", 0);
			if(!md5password.equals(sysUser.getPassword())){
				log.info("=============客户端平台密码错误");
				ResultObj robj = new ResultObj(ResultCode.RESULT_NULL, "客户端平台密码错误,请重新输入",null);
				return robj.toString();
			}
			String token=GenerativeToken.getToken();
			String jsonString = JSONObject.toJSONString(sysUserList.get(0));
			JSONObject userJson = JSONObject.parseObject(jsonString);
			redisService.setObjByTime(CommonConstant.BUS_DICTIONARY_PREFIX+token, userJson, 604800);
			SysUser user=sysUserList.get(0);
			
			HashMap<String, Object> map=new HashMap<String, Object>();
			map.put("userId", user.getId());
			map.put("userName", user.getUserName());
			map.put("roleId", user.getRoleId());
			map.put("deptId", user.getDeptId());
			map.put("officeId", user.getOfficeId());
			map.put("token", token);
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常",null);
			return robj.toString();
		}
	}
	/**
	 * 获取到前端权限
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/getMenu",method = RequestMethod.POST)
	@ResponseBody
	public String getMenu(String userId){
		try {
			SysUser sysUser=sysUserService.get(userId);
			List<MenuNode> munuList=sysMenuService.menuRight(sysUser,1);
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",munuList);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "",null);
			return robj.toString();
		}
	}
	/**
	 * 得到对应字典
	 * @return
	 */
	@RequestMapping(value="/getData",method = RequestMethod.POST)
	@ResponseBody
	public String getData(String userId){
		try{
			HashMap<String, Object> map=new HashMap<String, Object>();
			//报案方式
			List<Map<String, String>> reportTypes = dictService.getDicts("report_type");
			if(reportTypes!=null && reportTypes.size()>0) {
				map.put("reportTypes", reportTypes);
			}else{
				map.put("reportTypes", null);
			}
			//赔付方式
			List<Map<String, String>> payTypes = dictService.getDicts("pay_type");
			if(payTypes!=null && payTypes.size()>0) {
				map.put("payTypes", payTypes);
			}else{
				map.put("payTypes", null);
			}
			//工单状态
			List<Map<String, String>> orderStatus = dictService.getDicts("order_status");
			if(orderStatus!=null && orderStatus.size()>0) {
				map.put("orderStatus", orderStatus);
			}else{
				map.put("orderStatus", null);
			}
			//SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
			SysUser sysUser=userService.get(userId);
			//获取外勤人员列表
			List<SysUser> users = userService.listByOfficeAndRoleType("4", sysUser);
			if(users!=null && users.size()>0) {
				map.put("users", users);
			}else{
				map.put("users", null);
			}
			//外勤公司
			WherePrams officeWhere=Method.where("1", C.EQ, "1");
			String officeId=sysUser.getOfficeId();
			if(officeId!=null && officeId.length()>0){
				officeWhere.and("type", C.EQ, "1");
				List<SysOffice> office=sysOfficeService.list(officeWhere);
				map.put("office", office);
			}else{
				map.put("office", null);
			}
			
			//保险公司
			List<Map<String, String>> insuranceCompany = dictService.getDicts("insurance_company");
			if(insuranceCompany!=null && insuranceCompany.size()>0) {
				map.put("insuranceCompany", insuranceCompany);
			}else{
				map.put("insuranceCompany", null);
			}
			//外修配件及步骤
			List<SysDictDto> partsList = dictService.getDictsDto("parts_",1);
			if(partsList!=null && partsList.size()>0) {
				for (SysDictDto sysDict : partsList) {
					String type=sysDict.getType();
					if(type!=null && type.length()>0){
						List<SysDictDto> partsData = dictService.getDictsDto(type,0);
						sysDict.setListDate(partsData);
					}
				}
				map.put("partsList", partsList);
			}else{
				map.put("partsList", null);
			}
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",map);
			return robj.toString();
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "",null);
			return robj.toString();
		}
	}
}











